import logging

from PyQt4 import QtCore

from fogmini import global_objects
from fogmini.utils import get_config_value

from case import Case
from list_people import get_name_for_email

class AssignedCasesModel(QtCore.QAbstractListModel):
    def __init__(self, *args, **kwargs):
        QtCore.QAbstractListModel.__init__(self, *args, **kwargs)

        self._data = None

        global_objects.app.login_successful.connect(self.get_assigned_cases)

    def index(self, row, column, parent):
        return self.createIndex(row, column)

    def parent(self):
        return QtCore.QModelIndex()

    def data(self, index, role):
        if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
            return self._data[index.row()]
        else:
            return QtCore.QVariant()

    def rowCount(self, parent):
        if self._data is None:
            return 0
        else:
            return len(self._data)

    def headerData(self, section, orientation, role):
        return "Case Name"

    def get_assigned_cases(self):
        name = get_name_for_email(get_config_value("username", "").toString())
        logging.getLogger("AssignedCasesModel").debug("Getting cases assigned to %s." % (name, ))

        cases = Case.search(q='assignedto:"%s"' % (name, ))
        print cases

        self._data = ["%s: %s" % (case.id, case.title) for case in cases]
